package org.me.CreateManyImage;

import java.util.ArrayList;

import org.me.CreateManyImage.GraphicsObject.Coordinates;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Panel extends SurfaceView implements SurfaceHolder.Callback {

	private TutorialThread _thread;
	private ArrayList<GraphicsObject> listObj = new ArrayList<GraphicsObject>();
	Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
	public Panel(Context context) {
		super(context);
		getHolder().addCallback(this);
		_thread = new TutorialThread(getHolder(), this);
		setFocusable(true);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		synchronized(_thread.getSurfaceHolder())
		{
			if(event.getAction() == MotionEvent.ACTION_DOWN)
			{
				GraphicsObject graphics  = new GraphicsObject(bitmap);
				graphics.GetCoordinates().SetX((int)event.getX()-graphics.GetBitmap().getWidth()/2);
				graphics.GetCoordinates().SetY((int)event.getY()-graphics.GetBitmap().getHeight()/2);
				listObj.add(graphics);
			}
		}
		
		return true;
		
	
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		
		canvas.drawColor(Color.BLACK);
		Bitmap bitmap;
		GraphicsObject.Coordinates coor;
		for(GraphicsObject ob:listObj)
		{
			bitmap = ob.GetBitmap();
			canvas.drawBitmap(bitmap, ob.GetCoordinates().getX(), ob.GetCoordinates().getY(),null);
			
		}
		
		
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		_thread.setRunning(true);
		_thread.start();
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		boolean retry = true;
        _thread.setRunning(false);
        while (retry) {
            try {
                _thread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
		
	}

}
